import { DavinciBlockLink } from './custom-types.ts';
import { h, VNode } from 'snabbdom';
import { SlateTransforms, IDomEditor, SlateElement, DomEditor } from '@wangeditor/editor';
export function renderDavinciBlock(elem: SlateElement, children: VNode[] | null, editor: IDomEditor): VNode {
	const { link, content } = elem as unknown as DavinciBlockLink;
	const config = editor.getConfig();
	const { color = '#000', selectedColor = '#000', backgroundColor = 'rgba(0,0,0,0.1)', attrs = {} } = config.EXTEND_CONF?.['davinci-link'] ?? {};
	const selected = DomEditor.isNodeSelected(editor, elem);
	const davinciVnode = h(
		'span',
		{
			props: { contentEditable: false }, // HTML 属性，驼峰式写法
			style: {
				display: 'inline-block',
				padding: '0 3px',
				margin: '0 1px',
				color: selected ? selectedColor : color,
				background: backgroundColor,
				fontWeight: 'bold',
				cursor: 'pointer',
				animation: selected ? 'davinci-block-blink 1s linear 0s infinite' : 'none'
			},
			dataset: { type: 'davinci-link' },
			attrs: {
				...attrs,
				href: link
			},
			on: {
				mousedown(e) {
					(e.target as HTMLSpanElement).setAttribute('draggable', 'true');
				},
				mouseup(e) {
					(e.target as HTMLSpanElement).removeAttribute('draggable');
				},
				async contextmenu(e) {
					e.preventDefault();
					let res = await config.EXTEND_CONF?.['davinci-link']?.onRightClick?.(elem);
					if (res) {
						SlateTransforms.removeNodes(editor, {
							match: n => DomEditor.checkNodeType(n, 'davinci-link')
						});
					}
				},
				click() {
					const { children, ...rest } = elem;
					config.EXTEND_CONF?.['davinci-link']?.onClick?.(rest);
				}
			}
		},
		[`{${content}}`]
	);

	return davinciVnode;
}

const conf = {
	type: 'davinci-link', // 节点 type ，重要！！！
	renderElem: renderDavinciBlock
};

export default conf;
